#!/usr/bin/env python
"""
Addama Resource Services

Provides an API for resource services via addama-rest.

For more information, please see the documentation in README.txt, or simply
issue help() on any function or module contained within this package.

For license information, please see LICENSE.txt.


Author: Tom Robinson <trobinson@systemsbiology.org>
Initial Revision: April 14th, 2010

"""

# Imports

import cookielib
import urllib2

# Compatibility: JSON support was added to the Python tree in 2.6. 
# We use SimpleJSON for lower revisions.
try: 
    import json 
except ImportError: 
    import simplejson as json


# Functions
def getFile(uri, authCookies=None):
#print "getting file " + uri
	if not authCookies:
		authCookies=cookielib.CookieJar()
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(authCookies))

	fluffy_data = opener.open(uri)
	return fluffy_data
	#name = uri.split("/")[-1]
	#localFile = open(name, 'w')
	#localFile.write(fluffy_data.read())
	#localFile.close()

def getJSON(url, authCookies=None):
    """Gets the supplied resource
    Returns the JSON for this resource on success, None otherwise"""
    
    # Preconditions
    if len(url) == 0:
        raise ValueError

    # Build a cookie jar object if one isn't provided    
    if not authCookies:
        authCookies=cookielib.CookieJar()

    # Open the URL and extract its JSON data
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(authCookies))
    try:
	print "opening " + url
        request = opener.open(url)
        return json.loads(request.read())
    except IOError:
        return None
    # @note Malformed JSON will crash if it's received from the server


def postJSON(url, authCookies=None):
    """Posts JSON to this resource
    Returns the JSON-Formatted UUID for this resource on success, None otherwise"""
    
    # Code-wise, getJSON and postJSON are the same except when a file is
    # uploaded. Python intelligently selects between GET and POST, depending on
    # whether the request contains data (Request.has_data() == True)

    # Preconditions
    if len(url) == 0:
        raise ValueError

    # Build a cookie jar object if one isn't provided    
    if not authCookies:
        authCookies=cookielib.CookieJar()

    # Open the URL and extract its JSON data
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(authCookies))
    try:
        request = opener.open(url)
        print dir(request)
        return json.loads(request.read())
    except IOError:
        return None
    # @note Malformed JSON will crash if it's received from the server


# Output help text if this script is invoked directly
if __name__ == "__main__":
    print """
This script should not be run directly.

To include it in your project, simply import it from addama:
import <directory>
from <module> import <submodule>

For example:
import addama.api
from addama import api

(Note these two invocations differ as to the syntax of the final module)

"""

